﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Runtime.InteropServices;

namespace Obra.Common
{
    public class Credential
    {
        public static SecureString StringToSecureString(string data)
        {
            SecureString secureString = new SecureString();
            data.ToCharArray().ToList().ForEach(x => secureString.AppendChar(x));

            return secureString;
        }

        /// <summary>
        /// Convert a SecureString to a plain-text string.
        /// </summary>
        /// <param name="securePassword">
        /// Password to convert from a SecureString to plain-text.
        /// </param>
        /// <returns></returns>
        /// <remarks>
        /// <para>
        /// I wish, that I didn't have to do this, but unfortunately there does
        /// not appear to be way to use SecureString througout.
        /// </para>
        /// <para>
        /// This code is from http://blogs.msdn.com/b/fpintos/archive/2009/06/12/how-to-properly-convert-securestring-to-string.aspx.
        /// </para>
        /// </remarks>
        public static string SecureStringToString(SecureString securePassword)
        {
            if (securePassword == null)
            {
                throw new ArgumentNullException();
            }

            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }

    }
}
